#include "head.h"


void* start_routine(void* arg)
{
    printf("start_routine\n");
    Pool_t* pool = (Pool_t*)arg;

    while(1)
    {
        pthread_mutex_lock(&pool->mutex);

        while(pool->Q->size == 0 && pool->alive == true)
            pthread_cond_wait(&pool->cond, &pool->mutex);

        if(pool->alive == false)
        {
            pthread_mutex_unlock(&pool->mutex);
            printf("进程号:%d 子线程%ld:已退出\n", getpid(), pthread_self());
            pthread_exit(NULL);
        }

        int sock_fd = pop_queue(pool->Q);

        pthread_mutex_unlock(&pool->mutex);

        while(1)
        {   
            if(son(sock_fd) == 0)
                break;      
        }
 
    }

    return NULL;
}

Pool_t* create_pool(void)
{
    Pool_t* pool = (Pool_t*)malloc(sizeof(Pool_t));
    pool->Q = creat_queue();
    pool->number = N;
    pthread_mutex_init(&pool->mutex, NULL);
    pthread_cond_init(&pool->cond, NULL);
    for(int i = 0; i < N; ++i)
    {
        pthread_create(&pool->pthread_arr[i], NULL, start_routine, pool);
        printf("进程号:%d 线程%ld:已创建\n", getpid(), pool->pthread_arr[i]);
    }

    pool->alive = true;

    printf("create_pool\n");
    return pool;
}


void awaken(Pool_t* pool, int sock_fd)
{
    if(push_queue(pool->Q, sock_fd) == -1)
    {
        printf("服务器繁忙\n");
        close(sock_fd);
    }   
    else
        pthread_cond_broadcast(&pool->cond);

    printf("awaken\n");
}

int son(int sock_fd)
{

    while(1)
    {
        // 读文件名
        FileName_t file_name;
        int ret = recv(sock_fd, &file_name.name, sizeof(file_name), MSG_WAITALL);
        if(ret == -1)
            error(1 ,errno, "recv");
        else if(ret == 0)
            break;

        // 打开文件
        int file_fd = open(file_name.name, O_RDONLY);
        if(file_fd == -1)
            error(1, errno, "open");

        // 发文件信息
        struct stat statbuf;
        fstat(file_fd, &statbuf);
        send(sock_fd, &statbuf, sizeof(statbuf), MSG_NOSIGNAL);

        // 发送文件
        while(1)
        {
            char buf[1024] = {0};
            int count = read(file_fd, buf, sizeof(buf));
            if(count == 0)
                break;
            int ret = send(sock_fd, buf, count, MSG_NOSIGNAL);
            fprintf(stderr, "\rcount = %-4d", count);
        }
        printf("\n");
        close(file_fd);
        // 计算哈希值
        file_hash(file_name.name);
    }

    close(sock_fd);
    printf("已断开连接\n");
    return 0;
}
